<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.module-wrap{
  padding:10px;
  width: 100%;
  box-sizing: border-box;
  h2{
    text-align: center;
    line-height: 32px;
    font-size: 18px;
  }
  .btn{
    margin:0 0 10px;
    color:#333;
  }
}
.map{
  width:100%; 
  height: 180px;
}
</style>
<!-- 组件 -->
<template>
  <div class="module-wrap">
    <h2>点击效果(按钮)</h2>
    <button class="btn btn-default">default</button>
    <button class="btn btn-primary">primary</button>
    <button class="btn btn-delete">delete</button>
    <hr/>
    <h2>跳转滑动效果</h2>
    <router-link :to="{ path: '/transition/step1'}" tag="button" class="btn btn-default">点击查看效果</router-link>
    <hr/>
    <h2>时间选择（vux-datetime）</h2>
    <div class="ll-cell">
      <div>日期选择</div>
      <div class="flex1 txt-rit">
        <datetime v-model="valueStart1" @on-change="change1" title="单选">{{valueStart1}}</datetime>
      </div>
    </div>
    <div class="ll-cell">
      <div>日期时间点选择</div>
      <div class="flex1 txt-rit">
        <datetime v-model="valueStart2" @on-change="change2" format="YYYY-MM-DD HH:mm">{{valueStart2}}</datetime>
      </div>
    </div>
    <div class="ll-cell">
      <div>时间点选择</div>
      <div class="flex1 txt-rit">
        <datetime v-model="valueStart2" @on-change="change2" format="HH:mm:ss">{{valueStart2}}</datetime>
      </div>
    </div>
    <hr/>
    <h2>二维码生成</h2>
    <qrcode :value="valueurl" :size="200"></qrcode>
    <hr/>
    <h2>城市选择省市区</h2>
    <div class="address-wrap">
      <x-address title="地址" v-model="addressValue" :list="addressData" placeholder="请选择" value-text-align="right" >
      </x-address>
    </div>
    <hr/>
    <h2>弹出框</h2>
    <div class="ll-cell">
      <div>toast</div>
      <div class="flex1 txt-rit"><button class="btn btn-default" @click="click1">点击(带图标)</button></div>
    </div>
    <div class="ll-cell">
      <div>toast</div>
      <div class="flex1 txt-rit"><button class="btn btn-default" @click="click2">点击（仅文字）</button></div>
    </div>
    <div class="ll-cell">
      <div>confirm</div>
      <div class="flex1 txt-rit"><button class="btn btn-default" @click="click3">点击</button></div>
    </div>
    <div class="ll-cell">
      <div>加载中</div>
      <div class="flex1 txt-rit">
        <button class="btn btn-default" @click="showLoad=true">点击</button>
        <div class="loader-wrap" v-if="showLoad"></div>
      </div>
    </div>
    <div class="ll-cell">
      <div>自定义弹出</div>
      <div class="flex1 txt-rit"><button class="btn btn-default" @click="showDialogStyle=true">点击</button></div>
      <x-dialog v-model="showDialogStyle" hide-on-blur :dialog-style="{'max-width': '100%', width: '100%', height: '50%', 'background-color': 'transparent'}">
        <p style="color:#fff;text-align:center;" @click="showDialogStyle = false">
          <span style="font-size:30px;">HELLO WORLD</span>
          <br>
          <br>
          关闭
        </p>
      </x-dialog>
    </div>
    <hr/>
    <h2>下拉组件</h2>
    <div class="ll-cell">
      <popup-picker class="picker-wrap" 
            title="一级选择" 
            :data="customTypeList" 
            placeholder="点击选择" 
            value-text-align="right"
            :show-name="customTypeshow"
            v-model="customType"></popup-picker>
    </div>
    <div class="ll-cell">
      <popup-picker class="picker-wrap" 
            title="二级选择" 
            :data="list2" 
            placeholder="点击选择" 
            value-text-align="right"
            :show-name="value2show"
            v-model="value2"></popup-picker>
    </div>
    <hr/>
    <h2>单选\多选</h2>
    <group>
      <radio :options="radio001" @on-change="change3"></radio>
      <x-switch title="单选" v-model="stringValue" prevent-default @on-click="click4"></x-switch>
    </group>
    <checklist ref="demoObject" :options="objectList" v-model="objectListValue" @on-change="change4"></checklist>
    <hr/>
    <h2>单据明细，显示统一订单（商品）明细</h2>
    <goods-detail></goods-detail>
    <hr/>
    <h2>图片上传</h2>
    <uploader-file v-model="imgList"></uploader-file>
    图片base64的数组值：{{imgList}}
    <hr/>
    <h2>数据加载封装（包含定时器，隔断时间请求接口）</h2>
    <button class="btn btn-default" @click="getdata">获取数据</button><hr/>
    <h2>地图组件，定位当前位置.计算两点间的公里数和驾车时间。规划两点间驾车路线</h2>
    <div id="container" class="map"></div>
    <button class="btn btn-default" @click="getCurrent">定位当前位置</button>
    <button class="btn btn-default" @click="driving_route">规划路线</button>
    <div id="result"></div>
    <hr/>

  </div>
</template>

<script>
import goodsDetail from '@/components/share/goodsDetail.vue';
import uploaderFile from '@/components/share/uploaderFileReader.vue';
import imgstart from "@/assets/icon/start.png";
import imgend from "@/assets/icon/end.png";

export default {
  name: 'module',
  components: {
    goodsDetail,
    uploaderFile
  },
  data () {
    return {
      valueStart1:'请选择',
      valueStart2:'请选择',
      addressValue:[],
      addressData: this.ChinaAddressV3Data,
      valueurl:"www.baidu.com",
      //客户类型
      customTypeshow: true,
      customType: [],
      customTypeList: [
        [
          {
            value: "1",
            name: "医院"
          },
          {
            value: "4",
            name: "公司"
          }
          
        ]
      ],
      //等级
      value2show: true,
      value2: [],
      list2: [
        [
          {
            value: "1",
            name: "一级"
          },
          {
            value: "2",
            name: "二级"
          },
          {
            value: "3",
            name: "三级"
          }
        ],
        [
          {
            value: "1",
            name: "甲等"
          },
          {
            value: "2",
            name: "乙等"
          },
          {
            value: "3",
            name: "丙等"
          }
        ]
      ],
      showDialogStyle:false,
      radio001: [ 'China', 'Japan' ],
      stringValue:false,
      objectList: [{key: '1', value: '001 value'}, {key: '2', value: '002 value'}, {key: '3', value: '003 value'}],
      objectListValue: ['1'],
      showLoad:false,
      imgList:''
    }
  },
  created(){
    // 启动定时器调用方法
    // this.intervalFun();
    
  },
  mounted(){
    this.$nextTick(function() {
      this.getMap();
    })
  },
  methods:{
    change1(val){
      console.log(val)
    },
    change2(val){
      console.log(val)
    },
    click1(){
      this.$vux.toast.show({
        type:'success',//success, warn, cancel, text
        text: 'Hello World',
        onShow () {
          console.log('Plugin: I\'m showing')
        },
        onHide () {
          console.log('Plugin: I\'m hiding')
        }
      })
    },
    click2(){
      this.$vux.toast.text('hello lianlian')
    },
    click3(){
      this.$vux.confirm.show({
        title: 'Title',
        content: 'Content',
        onShow () {
          console.log('plugin show')
        },
        onHide () {
          console.log('plugin hide')
        },
        onCancel () {
          console.log('plugin cancel')
        },
        onConfirm () {
          console.log('plugin confirm')
        }
      })
    },
    change3 (value, label) {
      console.log('change:', value, label)
    },
    click4(newVal, oldVal){
      console.log(newVal, oldVal)
      this.stringValue = newVal
    },
    change4 (val, label) {
      console.log('change4', val, label)
    },
    getdata() {
      var self = this;
      var query = {
        searchWord: "",
        typecode: "",
        days: "",
        page: 1,
        size: 6
      };
      this.Ajax.post("getNewslist", query).then(function(resp) {
        self.todolist = resp.data.list;
      });
    },
    intervalFun(){
      var _this = this;
      setInterval(_this.getdata,1000);
    },
    getMap(){
      var map = new AMap.Map('container',{
            resizeEnable: true,
            zoom: 10,
            center: [116.480983, 40.0958]//经纬度值
          });
    },
    getCurrent(){
      var map = new AMap.Map('container'), 
          geolocation = null, 
          result = document.getElementById('result');
      map.plugin('AMap.Geolocation', function () {
        geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位，默认:true
          timeout: 10000,          //超过10秒后停止定位，默认：无穷大
          maximumAge: 0,           //定位结果缓存0毫秒，默认：0
          convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true,        //显示定位按钮，默认：true
          buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
          buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
      });
      
      /*
       *解析定位结果
       */
      function onComplete (data) {
        var str = '<p>定位成功</p>';
        str += '<p>经度：' + data.position.getLng() + '</p>';
        str += '<p>纬度：' + data.position.getLat() + '</p>'; 
        str += '<p>精度：' + data.accuracy + ' 米</p>';
        str += '<p>是否经过偏移：' + (data.isConverted ? '是' : '否') + '</p>';
        console.log(str);
      };
      /*
       *解析定位错误信息
       */
      function onError (data) {
        var str = '<p>定位失败</p>';
        str += '<p>错误信息：'
        switch(data.info) {
          case 'PERMISSION_DENIED':
            str += '浏览器阻止了定位操作';
            break;
          case 'POSITION_UNAVAILBLE':
            str += '无法获得当前位置';
            break;
          case 'TIMEOUT':
            str += '定位超时';
            break;
          default:
            str += '未知错误';
            break;
        }
        str += '</p>';
        console.log(str);
      };

    },
    driving_route(){
      var map = new AMap.Map('container');
      //起、终点
      var start_xy = new AMap.LngLat(116.379018,39.865026);
      var end_xy = new AMap.LngLat(116.321139, 39.896028);
      //驾车导航
      var MDrive;
      map.plugin(["AMap.Driving"], function() {
        var DrivingOption = {
          //驾车策略，包括 LEAST_TIME，LEAST_FEE, LEAST_DISTANCE,REAL_TRAFFIC
          policy: AMap.DrivingPolicy.LEAST_TIME 
        };        
        MDrive = new AMap.Driving(DrivingOption); //构造驾车导航类 
        AMap.event.addListener(MDrive, "complete", driving_routeCallBack); //返回导航查询结果
        MDrive.search(start_xy, end_xy); //根据起终点坐标规划驾车路线
      });
      //导航结果展示
      var route_text,steps,roaddistance=0,roadtime=0;
      function driving_routeCallBack(data) {
        var routeS = data.routes;
        if (routeS.length <= 0) {
          document.getElementById("result").innerHTML = "未查找到任何结果!<br />建议：<br />1.请确保所有字词拼写正确。<br />2.尝试不同的关键字。<br />3.尝试更宽泛的关键字。";
        } 
        else{ 
          route_text="";
          for(var v =0; v< routeS.length;v++){
            //驾车步骤数
            roaddistance += routeS[v].distance;
            roadtime += routeS[v].time
            steps = routeS[v].steps
            var route_count = steps.length;
            //行车距离（米）
            var distance = routeS[v].distance;
            //拼接输出html
            for(var i=0 ;i< steps.length;i++){
              route_text += "<tr><td align=\"left\">" + (i+1) +"." +steps[i].instruction  + "</td></tr>";
            }
          }
          
          roadtime = timeFormat(roadtime)
          //输出行车路线指示
          route_text = "<table cellspacing=\"5px\"><tr><td style=\";\">路线驾车时长"+roadtime+"</td></tr><tr><td>距离："+(roaddistance/1000)+"公里</td></tr><tr><td>&nbsp;&nbsp;北京南站</td></tr>" + route_text + "<tr><td>&nbsp;&nbsp;北京西站</td></tr></table>";
          document.getElementById("result").innerHTML = route_text;
          drivingDrawLine();
        }   
      };
      //时间格式整理
      function timeFormat(time){
        var minute = time/60;
        var txt='';
        if(minute > 60){
          txt = Math.floor(minute/60)+'小时' ;
          if(minute%60>0){
            txt += Math.ceil(minute%60)+'分钟'
          }
        }else{
          txt = Math.ceil(minute)+'分钟';
        };
        return txt;
      }
      //绘制驾车导航路线
      function drivingDrawLine(s) {
        //起点、终点图标
        var sicon = new AMap.Icon({
          image: imgstart,
          size:new AMap.Size(44,44),
          // imageOffset: new AMap.Pixel(-334, -180)
        });
        var startmarker = new AMap.Marker({
          icon : sicon, //复杂图标
          visible : true, 
          position : start_xy,
          map:map,
          offset : {
            x : -16,
            y : -40
          }
        });
        var eicon = new AMap.Icon({
          image: imgend,
          size:new AMap.Size(44,44),
          // imageOffset: new AMap.Pixel(-334, -134)
        });
        var endmarker = new AMap.Marker({
          icon : eicon, //复杂图标
          visible : true, 
          position : end_xy,
          map:map,
          offset : {
            x : -16,
            y : -40
          }
        });
        //起点到路线的起点 路线的终点到终点 绘制无道路部分
        var extra_path1 = new Array();
        extra_path1.push(start_xy);
        extra_path1.push(steps[0].path[0]);
        var extra_line1 = new AMap.Polyline({
          map: map,
          path: extra_path1,
          strokeColor: "#9400D3",
          strokeOpacity: 0.7,
          strokeWeight: 4,
          strokeStyle: "dashed",
          strokeDasharray: [10, 5]
        });
      
        var extra_path2 = new Array();
        var path_xy = steps[(steps.length-1)].path;
        extra_path2.push(end_xy);
        extra_path2.push(path_xy[(path_xy.length-1)]);
        var extra_line2 = new AMap.Polyline({
          map: map,
          path: extra_path2,
          strokeColor: "#9400D3",
          strokeOpacity: 0.7,
          strokeWeight: 4,
          strokeStyle: "dashed",
          strokeDasharray: [10, 5]
        });
        
        var drawpath = new Array(); 
        for(var s=0; s<steps.length; s++) {
          var plength = steps[s].path.length;
          for (var p=0; p<plength; p++) {
            drawpath.push(steps[s].path[p]);
          }
        }
        var polyline = new AMap.Polyline({
          map: map,
          path: drawpath,
          strokeColor: "#9400D3",
          strokeOpacity: 0.7,
          strokeWeight: 4,
          strokeDasharray: [10, 5]
        });
        map.setFitView();
      };
    }
  }
}
</script>


